import React, { useEffect, useState } from "react";
import { getNodes } from "../../api/cdnNodeApi";
import CNameAPI from "../../api/CNameApi";
import { ARecord, ARecordCreate } from "../../types/CdnARecord";

interface Node {
    id: number;
    name: string;
    host: string;
}
const ARecordPage = () => {
    const [records, setRecords] = useState<ARecord[]>([]);
    const [nodes, setNodes] = useState<Node[]>([]);
    const [showModal, setShowModal] = useState(false);
    const [currentRecord, setCurrentRecord] = useState<Partial<ARecordCreate> | null>(null);

    const fetchRecords = async () => {
        const res = await CNameAPI.getAll();
        setRecords(res.data);
    };

    const fetchNodes = async () => {
        const res = await getNodes();
        setNodes(res);
    };

    useEffect(() => {
        fetchRecords();
        fetchNodes();
    }, []);

    const handleDeploy = async (id: number) => {
        if (!window.confirm("确定要部署该记录吗？")) return; // 添加确认
        try {
            const res = await CNameAPI.deploy(id);
            alert(res.data.message);
            fetchRecords(); // 如果部署会影响列表状态，可刷新
        } catch (error: any) {
            alert(error?.response?.data?.detail || "部署失败");
        }
    };

    const handleOffline = async (id: number) => {
        if (!window.confirm("确定要下线该记录吗？")) return; // 添加确认
        try {
            const res = await CNameAPI.offline(id);
            alert(res.data.message);
            fetchRecords(); // 如果部署会影响列表状态，可刷新
        } catch (error: any) {
            alert(error?.response?.data?.detail || "部署失败");
        }
    };
    const handleDelete = async (id: number) => {
        if (!window.confirm("确定要删除该记录吗？")) return;
        await CNameAPI.delete(id);
        fetchRecords();
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!currentRecord?.domain || !currentRecord.node_ids?.length) {
            alert("请填写域名并选择节点");
            return;
        }

        let recordId: number | undefined;

        try {
            if ((currentRecord as any).id) {
                const res = await CNameAPI.update((currentRecord as any).id, currentRecord);
                recordId = (currentRecord as any).id;
            } else {
                const res = await CNameAPI.create(currentRecord);
                recordId = res.data.id; // 假设接口返回新记录的 id
            }

            // 如果勾选了启用，则调用部署接口
            if (currentRecord.status && recordId) {
                const deployRes = await CNameAPI.deploy(recordId);
                alert(deployRes.data.message);
            }

            setShowModal(false);
            setCurrentRecord(null);
            fetchRecords();
        } catch (error: any) {
            alert(error?.response?.data?.detail || "操作失败");
        }
    };

    const handleEdit = (record: ARecord) => {
        setCurrentRecord({ ...record, node_ids: record.node_ids || [] });
        setShowModal(true);
    };

    return (
        <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
            <div className="flex justify-between items-start mb-6">
                {/* 左侧：标题 + 提示 */}
                <div>
                    <h1 className="text-3xl font-bold text-gray-900 dark:text-white">CNAME 配置</h1>
                    <p className="mt-2 text-sm text-yellow-600 dark:text-yellow-400">
                        ⚠️ 注意：这里配置的 CNAME 需要在域名 DNS 中增加一条{" "}
                        <code className="bg-gray-200 dark:bg-gray-800 px-1 rounded">NS</code>{" "}
                        记录指向{" "}
                        <code className="bg-gray-200 dark:bg-gray-800 px-1 rounded">DNS服务器(即本服务器对应dns)</code>
                    </p>
                </div>

                {/* 右侧：新增按钮 */}
                <button
                    className="bg-blue-600 text-white py-2 px-5 rounded-lg hover:bg-blue-700 shadow"
                    onClick={() => {
                        setCurrentRecord({ domain: "", ttl: 30, status: false, node_ids: [] });
                        setShowModal(true);
                    }}
                >
                    + 新增记录
                </button>
            </div>


            <div className="overflow-x-auto rounded-lg shadow">
                <table className="w-full text-sm text-left text-gray-600 dark:text-gray-300">
                    <thead className="text-xs uppercase bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
                        <tr>
                            <th className="px-6 py-3">ID</th>
                            <th className="px-6 py-3">域名</th>
                            <th className="px-6 py-3">TTL</th>
                            <th className="px-6 py-3">节点</th>
                            <th className="px-6 py-3 text-right">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {records.map((rec) => (
                            <tr
                                key={rec.id}
                                className="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"
                            >
                                <td className="px-6 py-4">{rec.id}</td>
                                <td className="px-6 py-4">{rec.domain}</td>
                                <td className="px-6 py-4">{rec.ttl}</td>
                                <td className="px-6 py-4">
                                    {rec.nodes && rec.nodes.length > 0
                                        ? rec.nodes.map((n) => n.name).join(", ")
                                        : "未绑定节点"}
                                </td>
                                <td className="px-6 py-4 flex justify-end space-x-2">
                                    <button
                                        className="bg-blue-500 text-white py-1.5 px-3 rounded hover:bg-blue-600"
                                        onClick={() => handleEdit(rec)}
                                    >
                                        编辑
                                    </button>

                                    {rec.status ? (
                                        <button
                                            className="bg-green-500 text-white py-1.5 px-3 rounded hover:bg-green-600"
                                            onClick={() => handleOffline(rec.id)}
                                        >
                                            下线
                                        </button>
                                    ) : (
                                        <button
                                            className="bg-green-500 text-white py-1.5 px-3 rounded hover:bg-green-600"
                                            onClick={() => handleDeploy(rec.id)}
                                        >
                                            部署
                                        </button>
                                    )}

                                    <button
                                        className="bg-red-500 text-white py-1.5 px-3 rounded hover:bg-red-600"
                                        onClick={() => handleDelete(rec.id)}
                                    >
                                        删除
                                    </button>
                                </td>
                            </tr>
                        ))}
                        {records.length === 0 && (
                            <tr>
                                <td colSpan={5} className="px-6 py-4 text-center text-gray-500">
                                    暂无数据
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>

            </div>

            {/* 弹窗 */}
            {showModal && (
                <div className="fixed inset-0 flex items-center justify-center z-50">
                    <div
                        className="absolute inset-0 bg-black bg-opacity-40"
                        onClick={() => setShowModal(false)}
                    ></div>
                    <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-full max-w-md">
                        <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-white">
                            {currentRecord?.id ? "编辑记录" : "新增记录"}
                        </h2>
                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div>
                                <label className="block text-gray-700 dark:text-gray-300 mb-1">
                                    域名
                                </label>
                                <input
                                    type="text"
                                    value={currentRecord?.domain || ""}
                                    onChange={(e) =>
                                        setCurrentRecord({ ...currentRecord, domain: e.target.value })
                                    }
                                    required
                                    className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                                />
                            </div>
                            <div>
                                <label className="block text-gray-700 dark:text-gray-300 mb-1">
                                    TTL
                                </label>
                                <input
                                    type="number"
                                    value={currentRecord?.ttl || 30}
                                    onChange={(e) =>
                                        setCurrentRecord({
                                            ...currentRecord,
                                            ttl: Number(e.target.value),
                                        })
                                    }
                                    className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                                />
                            </div>
                            <div className="flex items-center space-x-2">
                                <input
                                    type="checkbox"
                                    checked={currentRecord?.status ?? true}
                                    onChange={(e) =>
                                        setCurrentRecord({
                                            ...currentRecord,
                                            status: e.target.checked,
                                        })
                                    }
                                    className="w-4 h-4"
                                />
                                <span className="text-gray-700 dark:text-gray-300">启用记录</span>
                            </div>
                            <div>
                                <label className="block text-gray-700 dark:text-gray-300 mb-1">
                                    选择节点
                                </label>
                                {nodes.length > 0 ? (
                                    <div className="flex flex-wrap gap-2">
                                        {nodes.map((node) => (
                                            <label
                                                key={node.id}
                                                className={`px-3 py-1 border rounded cursor-pointer ${currentRecord?.node_ids?.includes(node.id)
                                                    ? "bg-blue-500 text-white"
                                                    : "bg-gray-50 dark:bg-gray-700"
                                                    }`}
                                            >
                                                <input
                                                    type="checkbox"
                                                    className="hidden"
                                                    checked={currentRecord?.node_ids?.includes(node.id) || false}
                                                    onChange={() => {
                                                        const selected = currentRecord?.node_ids || [];
                                                        setCurrentRecord({
                                                            ...currentRecord,
                                                            node_ids: selected.includes(node.id)
                                                                ? selected.filter((id) => id !== node.id)
                                                                : [...selected, node.id],
                                                        });
                                                    }}
                                                />
                                                {node.name}
                                            </label>
                                        ))}
                                    </div>
                                ) : (
                                    <div className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                                        暂无节点，请先{" "}
                                        <a
                                            href="/admin/cdn-node"
                                            className="text-blue-500 hover:underline"
                                        >
                                            前往新增节点
                                        </a>
                                        。
                                    </div>
                                )}
                            </div>

                            <div className="flex justify-end space-x-3 pt-2">
                                <button
                                    type="button"
                                    className="bg-gray-400 text-white py-2 px-4 rounded hover:bg-gray-500"
                                    onClick={() => setShowModal(false)}
                                >
                                    取消
                                </button>
                                <button
                                    type="submit"
                                    className="bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700"
                                >
                                    保存
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default ARecordPage;
